//
//  UITextView+Emoticon.swift
//  Weibo
//
//  Created by lzing on 16/4/3.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit

extension UITextView {
    ///  将表情文字转换为属性文本
    func emoticonText () -> String {
        var result = ""
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            // 如果dict中有NSAttachment标示是附件
            if let attachment = dict["NSAttachment"] as? LZTextAttachment {
                result += attachment.chs!
            } else {
                // 普通文本和emoji
                let subString = (self.attributedText.string as NSString).substringWithRange(range)
                result += subString
            }
        }
        return result
    }
    ///  插入表情的方法
    func insertEmoticon(emoticon : LZEmoticonModel) {
        // 添加emoji表情
        if let emoji = emoticon.emoji {
            // 插入表情
            insertText(emoji)
            return
        }
        // 图片表情
        if let fullPngPath = emoticon.fullPngPath {
            // 图片->附件->属性文本
            let attachment = LZTextAttachment()
            attachment.chs = emoticon.chs
            attachment.image = UIImage(named: fullPngPath)
            let wh = (font?.lineHeight ?? 20)
            attachment.bounds = CGRectMake(0, -3, wh, wh)
            // 可变富文本
            let attributeM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            // 设置附件属性
            attributeM.addAttribute(NSFontAttributeName , value: font!, range: NSRange(location: 0, length: 1))
            // 不能直接替换属性文本,取出老的文本
            let oldAttrM = NSMutableAttributedString(attributedString: attributedText)
            // 取出选中的范围
            let oldRange = selectedRange
            // 将附件添加到之间老的属性文本中
            oldAttrM.replaceCharactersInRange(oldRange, withAttributedString: attributeM)
            // 设置文本
            attributedText = oldAttrM
            // 移动光标到最后
            selectedRange = NSRange(location: oldRange.location + 1, length: 0)
            // 触发textView文本改变
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            // 主动调用代理方法
            delegate?.textViewDidChange?(self)
        }
    }
}
